package lan.agents;

import java.io.IOException;


import jade.core.AID;
import jade.core.Agent;
import jade.core.PlatformID;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.core.behaviours.ParallelBehaviour;
import jade.core.behaviours.SequentialBehaviour;
import jade.core.behaviours.SimpleBehaviour;
import jade.core.behaviours.TickerBehaviour;
import jade.core.behaviours.WakerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import jade.util.leap.ArrayList;
import jade.util.leap.List;
import vnu.ACLMessageX;
import vnu.JobAgent;
import vnu.Record;

public class ContentAgent extends JobAgent {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List newsList;
	private jade.core.AID dbagent;
	//private String result="";
	public static boolean isNewest ;
	protected void setup(){
		isNewest = false;
		super.setup();
		dbagent = new jade.core.AID(AGENT_DB, jade.core.AID.ISLOCALNAME);
		newsList = new ArrayList(); 
		
	  addBehaviour(new receiveMessage(this));
	
 addBehaviour(new MyTickerBehaviour(this,1000));
	}
class HandleMessage extends OneShotBehaviour{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private ACLMessage request;
		public HandleMessage(Agent a,ACLMessage request){
			super(a);
			this.request = request;
			
		}
		@Override
		public void action() {
			// TODO Auto-generated method stub
		//	int numberofrecords = Integer.parseInt(request.getContent());
			 //sendQueryToDBAgent(numberofrecords);
			String result="";
			for (int i = 0; i < newsList.size(); i++) {
				Record temp = (Record) newsList.get(i);
				result = result + temp.getContent()+"\n";
				
				
			}
			// addBehaviour(new WaitRespond(myAgent));
			 ACLMessage reply = request.createReply();
			 reply.setContent(result);
			 reply.setPerformative(ACLMessage.INFORM);
			 send(reply);
			 	
		}
		
		
	}



void processRequest(ACLMessage request){
		ACLMessageX message = new ACLMessageX("content", AGENT_DB);
		message.setContent(String.valueOf(request.getContent()));
		message.setPerformative(ACLMessage.REQUEST);
		sendMessage(message);
		SequentialBehaviour sq = new SequentialBehaviour();
		sq.addSubBehaviour(new WaitDBRespond(this));
		sq.addSubBehaviour(new HandleMessage(this, request));
		addBehaviour(sq);
	}
	 
class WaitDBRespond extends ParallelBehaviour{
	/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private
		WaitDBRespond(Agent a){
			super(a, 1);
			addSubBehaviour(new receiveNewsDBRespond(myAgent));
			addSubBehaviour(new WakerBehaviour(myAgent, 15000) {

				/**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				protected void handleElapsedTimeout() {
					System.err
							.println(myAgent + " Can not received any responds from DataBase Agent!");
				}
			});
		}

			
	}
	class receiveNewsDBRespond extends SimpleBehaviour{

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		/**
		 * 
		 */

		private boolean isFinished = false;
		public receiveNewsDBRespond(Agent a){
			super(a);
		}
		public void action(){
			ACLMessage receivedDataMsg = receive(MessageTemplate
					.MatchSender(dbagent));
			if(receivedDataMsg == null){
				block();
				return;
				
			}
			int performativ = receivedDataMsg.getPerformative();
			switch (performativ) {
			case ACLMessage.INFORM:{
				try {
					newsList = (ArrayList) receivedDataMsg.getContentObject();
					System.out.println("Reply from DBagent");
					for (int i = 0; i < newsList.size(); i++) {
						Record temp = (Record) newsList.get(i);
						System.out.println(temp.getId());
					}
				//	replyRequest(request)
				} catch (UnreadableException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				  
			}
				
				break;

			default:
				break;
			}
			isNewest = true;
			isFinished = true;
			
		}
		@Override
		public boolean done() {
			// TODO Auto-generated method stub
			return isFinished ;
		}
		
	}
	private class MyTickerBehaviour extends TickerBehaviour {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Agent agent;
		// long interval;
		int counter;
		public MyTickerBehaviour(Agent agent, long interval) {
			super(agent, interval);
			this.agent = agent;
			counter=0;
			System.out.println("State..."+getAgentState().getName());
		}
		@Override
		protected void onTick() {
		if(counter == 5){
				// move out
				AID remoteAMS = new AID("amm@toshiba-PC",AID.ISGUID);
				remoteAMS.addAddresses("http://toshiba-PC:7778/acc");
				PlatformID destination = new PlatformID(remoteAMS);
				agent.doMove(destination);
		}
		if (counter <= 10)
			System.out.println(counter++);
		
		}

	}
	@Override
	protected void afterMove() {
		// TODO Auto-generated method stub
		super.afterMove();
		System.out.println("I have moved successfully!");
		System.out.println(dbagent.getAddressesArray()[0]);
		System.out.println(agentmanagerAddress);
		///updateDBAgentinfo();
//		SequentialBehaviour sb = new SequentialBehaviour();
//		   sb.addSubBehaviour(new sendQuery(HOME));
//		   sb.addSubBehaviour(new WaitRespond(this));
//		   sb.addSubBehaviour(new MyTickerBehaviour(this, 3000));
//		   addBehaviour(sb);
//		
	}

	private class receiveMessage extends CyclicBehaviour{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public receiveMessage(Agent a){
			super(a);
		}
		
		public void action(){
			ACLMessage receivedMsg = receive(MessageTemplate.not(MessageTemplate.MatchSender(dbagent) ));
			//ACLMessage receivedMsg = myAgent.receive();

			if(receivedMsg != null){
			//	if(receivedMsg.getSender().getLocalName().equalsIgnoreCase(AGENT_DB)){
				//ACLMessage reply = msg.createReply();
				if(receivedMsg.getPerformative() == ACLMessage.REQUEST){
					processRequest(receivedMsg);
					
				}else {
					block();
				}
				
			}
		}
		}
//	}
}

	

